home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Information / Languages / C++ / C++ FAQ 2⁄4 < prev    next >
Encoding:
Internet Message Format  |  1994-12-08  |  34.6 KB  |  [TEXT/R*ch]

  1. Path: bloom-beacon.mit.edu!gatech!howland.reston.ans.net!pipex!uunet!library.erc.clarkson.edu!sun.soe.clarkson.edu!cline
  2. From: cline@sun.soe.clarkson.edu (Marshall Cline)
  3. Newsgroups: comp.lang.c++
  4. Subject: C++ FAQ: posting #2/4
  5. Followup-To: comp.lang.c++
  6. Date: 14 Nov 1994 00:26:25 GMT
  7. Organization: Paradigm Shift, Inc (training/consulting/OOD/OOP/C++)
  8. Lines: 834
  9. Sender: cline@sun.soe.clarkson.edu
  10. Distribution: world
  11. Expires: +1 month
  12. Message-ID: <3a6arh$gd7@library.erc.clarkson.edu>
  13. Reply-To: cline@parashift.com (Marshall Cline)
  14. NNTP-Posting-Host: sun.soe.clarkson.edu
  15. Summary: Please read this before posting to comp.lang.c++
  16.  
  17. comp.lang.c++ Frequently Asked Questions list (with answers, fortunately).
  18. Copyright (C) 1991-94 Marshall P. Cline, Ph.D.
  19. Posting 2 of 4.
  20. Posting #1 explains copying permissions, (no)warranty, table-of-contents, etc
  21.  
  22. ==============================================================================
  23. SECTION 9: Freestore management
  24. ==============================================================================
  25.  
  26. Q30: Does "delete p" delete the pointer "p", or the pointed-to-data, "*p"?
  27.  
  28. The pointed-to-data.
  29.  
  30. "delete" really means "delete the thing pointed to by."  The same abuse of
  31. English occurs when "free"ing the memory pointed to by a ptr in C ("free(p)"
  32. really means "free_the_stuff_pointed_to_by(p)").
  33.  
  34. ==============================================================================
  35.  
  36. Q31: Can I "free()" pointers allocated with "new"?  Can I "delete" pointers
  37.    alloc'd with "malloc()"?
  38.  
  39. No.
  40.  
  41. It is perfectly legal, moral, and wholesome to use malloc/free and new/delete
  42. in the same program, but it is illegal, immoral, and despicable to free a
  43. pointer allocated via new, or to delete a pointer allocated via malloc.
  44.  
  45. ==============================================================================
  46.  
  47. Q32: Why should I use "new" instead of trustworthy old malloc()?
  48.  
  49. Constructors/destructors, type safety, overridability.
  50.  
  51. Constructors/destructors: unlike "malloc(sizeof(Fred))", "new Fred()" calls
  52. Fred's constructor.  Similarly, "delete p" calls "*p"'s destructor.
  53.  
  54. Type safety: malloc() returns a "void*" which isn't type safe.  "new Fred()"
  55. returns a ptr of the right type (a "Fred*").
  56.  
  57. Overridability: "new" is an operator that can be overridden by a class, while
  58. "malloc" is not overridable on a per-class basis.
  59.  
  60. ==============================================================================
  61.  
  62. Q33: Why doesn't C++ have a "realloc()" along with "new" and "delete"?
  63.  
  64. To save you from disaster.
  65.  
  66. When realloc() has to copy the allocation, it uses a BITWISE copy operation,
  67. which will tear most C++ objects to shreds.  C++ objects should be allowed to
  68. copy themselves: they use their own copy constructor or assignment operator.
  69.  
  70. ==============================================================================
  71.  
  72. Q34: How do I allocate / unallocate an array of things?
  73.  
  74. Use new[] and delete[]:
  75.  
  76.     Fred* p = new Fred[100];
  77.     //...
  78.     delete [] p;
  79.  
  80. Any time you use the "[...]" in the "new" expression, you *!*MUST*!* use "[]"
  81. in the "delete" statement.  This syntax is necessary because there is no
  82. syntactic difference between a pointer to a thing and a pointer to an array of
  83. things (something we inherited from C).
  84.  
  85. ==============================================================================
  86.  
  87. Q35: What if I forget the "[]" when "delete"ing array allocated via "new
  88.    Fred[n]"?
  89.  
  90. All life comes to a catastrophic end.
  91.  
  92. It is the programmer's --not the compiler's-- responsibility to get the
  93. connection between new[] and delete[] correct.  If you get it wrong, neither a
  94. compile-time nor a run-time error message will be generated by the compiler.
  95. Heap corruption is a likely result.  Or worse.  Your program will probably die.
  96.  
  97. ==============================================================================
  98. SECTION 10: Debugging and error handling
  99. ==============================================================================
  100.  
  101. Q36: How can I handle a constructor that fails?
  102.  
  103. Throw an exception.
  104.  
  105. Constructors don't have a return type, so it's not possible to use error codes.
  106. The best way to signal constructor failure is therefore to throw an exception.
  107.  
  108. Before C++ had exceptions, we signaled constructor failure by putting the
  109. object into a "half baked" state (e.g., by setting an internal status bit).
  110. There was a query ("inspector") method to check this bit, that allowed clients
  111. to discover whether they had a live object.  Other member functions would also
  112. check this bit, and, if the object wasn't really alive, do a no-op (or perhaps
  113. something more obnoxious such as "abort()").  This was really ugly.
  114.  
  115. ==============================================================================
  116.  
  117. Q37: How should I handle resources if my constructors may throw exceptions?
  118.  
  119. Every data member inside your object should clean up its own mess.
  120.  
  121. If a constructor throws an exception, the object's destructor is NOT run.  If
  122. your object has already done something that needs to be undone (such as
  123. allocating some memory, opening a file, or locking a semaphore), this "stuff
  124. that needs to be undone" MUST be remembered by a data member inside the object.
  125.  
  126. For example, rather than allocating memory into a raw "Fred*" data member, put
  127. the allocated memory into a "smart pointer" member object, and the destructor
  128. of this smart pointer will delete the Fred object when the smart pointer dies.
  129.  
  130. ==============================================================================
  131. SECTION 11: Const correctness
  132. ==============================================================================
  133.  
  134. Q38: What is "const correctness"?
  135.  
  136. A good thing.
  137.  
  138. Const correctness uses the keyword "const" to ensure const objects don't get
  139. mutated.  E.g., if function "f()" accepts a "String", and "f()" wants to
  140. promise not to change the "String", you:
  141.  
  142.  * can either pass by value:    void  f(      String  s   )  { /*...*/ }
  143.  * or by constant reference:    void  f(const String& s   )  { /*...*/ }
  144.  * or by constant pointer:    void  f(const String* sptr)  { /*...*/ }
  145.  * but NOT by non-const ref:    void  f(      String& s   )  { /*...*/ }
  146.  * NOR by non-const pointer:    void  f(      String* sptr)  { /*...*/ }
  147.  
  148. Attempted changes to "s" within a fn that takes a "const String&" are flagged
  149. as compile-time errors; neither run-time space nor speed is degraded.
  150.  
  151. Declaring the "constness" of a parameter is just another form of type safety.
  152. It is almost as if a constant String, for example, "lost" its various mutative
  153. operations.  If you find type safety helps you get systems correct (it does;
  154. especially in large systems), you'll find const correctness helps also.
  155.  
  156. ==============================================================================
  157.  
  158. Q39: Should I try to get things const correct "sooner" or "later"?
  159.  
  160. At the very, very, VERY beginning.
  161.  
  162. Back-patching const correctness results in a snowball effect: every "const" you
  163. add "over here" requires four more to be added "over there."
  164.  
  165. ==============================================================================
  166.  
  167. Q40: What is a "const member function"?
  168.  
  169. A member function that inspects (rather than mutates) its object.
  170.  
  171.     class Fred {
  172.     public:
  173.       void f() const;
  174.     };      // ^^^^^--- this implies "fred.f()" won't change "fred"
  175.  
  176. This means that the ABSTRACT (client-visible) state of the object isn't going
  177. to change (as opposed to promising that the "raw bits of the object's struct
  178. aren't going to change).  C++ compilers aren't allowed to take the "bitwise"
  179. interpretation, since a non-const alias could exist which could modify the
  180. state of the object (gluing a "const" ptr to an object doesn't promise the
  181. object won't change; it only promises that the object won't change VIA THAT
  182. POINTER).
  183.  
  184. "const" member functions are often called "inspectors."  Non-"const" member
  185. functions are often called "mutators."
  186.  
  187. ==============================================================================
  188.  
  189. Q41: What do I do if I want to update an "invisible" data member inside a
  190.    "const" member function?
  191.  
  192. Use "mutable", or use "const_cast".
  193.  
  194. A small percentage of inspectors need to make innocuous changes to data members
  195. (e.g., a "Set" object might want to cache its last lookup in hopes of improving
  196. the performance of its next lookup).  By saying the changes are "inocuous," I
  197. mean that the changes wouldn't be visible from outside the object's interface
  198. (otherwise the method would be a mutator rather than an inspector).
  199.  
  200. When this happens, the data member which will be modified should be marked as
  201. "mutable" (put the "mutable" keyword just before the data member's declaration;
  202. i.e., in the same place where you could put "const").  This tells the compiler
  203. that the data member is allowed to change during a const member function.  If
  204. you can't use "mutable", you can cast away the constness of "this" via
  205. "const_cast".  E.g., in "Set::lookup() const", you might say,
  206.  
  207.     Set* self = const_cast<Set*>(this);
  208.  
  209. After this line, "self" will have the same bits as "this" (e.g., "self==this"),
  210. but "self" is a "Set*" rather than a "const Set*".  Therefore you can use
  211. "self" to modify the object pointed to by "this".
  212.  
  213. ==============================================================================
  214.  
  215. Q42: Does "const_cast" mean lost optimization opportunities?
  216.  
  217. In theory, yes; in practice, no.
  218.  
  219. Even if a compiler outlawed "const_cast", the only way to avoid flushing the
  220. register cache across a "const" member function call would be to ensure that
  221. there are no non-const pointers that alias the object.  This can only happen in
  222. rare cases (when the object is constructed in the scope of the const member fn
  223. invocation, and when all the non-const member function invocations between the
  224. object's construction and the const member fn invocation are statically bound,
  225. and when every one of these invocations is also "inline"d, and when the
  226. constructor itself is "inline"d, and when any member fns the constructor calls
  227. are inline).
  228.  
  229. ==============================================================================
  230. SECTION 12: Inheritance
  231. ==============================================================================
  232.  
  233. Q43: Is inheritance important to C++?
  234.  
  235. Yep.
  236.  
  237. Inheritance is what separates abstract data type (ADT) programming from OOP.
  238.  
  239. ==============================================================================
  240.  
  241. Q44: When would I use inheritance?
  242.  
  243. As a specification device.
  244.  
  245. Human beings abstract things on two dimensions: part-of and kind-of.  A Ford
  246. Taurus is-a-kind-of-a Car, and a Ford Taurus has-a Engine, Tires, etc.  The
  247. part-of hierarchy has been a part of software since the ADT style became
  248. relevant; inheritance adds "the other" major dimension of decomposition.
  249.  
  250. ==============================================================================
  251.  
  252. Q45: How do you express inheritance in C++?
  253.  
  254. By the ": public" syntax:
  255.  
  256.     class Car : public Vehicle {
  257.             //^^^^^^^^---- ": public" is pronounced "is-a-kind-of-a'
  258.       //...
  259.     };
  260.  
  261. We state the above relationship in several ways:
  262.  * Car is "a kind of a" Vehicle
  263.  * Car is "derived from" Vehicle
  264.  * Car is "a specialized" Vehicle
  265.  * Car is the "subclass" of Vehicle
  266.  * Vehicle is the "base class" of Car
  267.  * Vehicle is the "superclass" of Car (this not as common in the C++ community)
  268.  
  269. ==============================================================================
  270.  
  271. Q46: Is it ok to convert a pointer from a derived class to its base class?
  272.  
  273. Yes.
  274.  
  275. A derived class is a specialized version of the base class ("Derived is a
  276. kind-of Base").  The upward conversion is perfectly safe, and happens all the
  277. time (if I am pointing at a car, I am in fact pointing at a vehicle):
  278.  
  279.     void f(Vehicle* v);
  280.     void g(Car* c) { f(c); }    //perfectly safe; no cast
  281.  
  282. Note that the answer to this FAQ assumes we're talking about "public"
  283. inheritance; see below on "private/protected" inheritance for "the other kind".
  284.  
  285. ==============================================================================
  286.  
  287. Q47: Derived* --> Base* works ok; why doesn't Derived** --> Base** work?
  288.  
  289. C++ allows a Derived* to be converted to a Base*, since a Derived object is a
  290. kind of a Base object.  However trying to convert a Derived** to a Base** is
  291. (correctly) flagged as an error (if it was allowed, the Base** could be
  292. dereferenced (yielding a Base*), and the Base* could be made to point to an
  293. object of a DIFFERENT derived class.  This would be an error.
  294.  
  295. As a corollary, an array of Deriveds is-NOT-a-kind-of array of Bases.  At
  296. Paradigm Shift, Inc. we use the following example in our C++ training sessions:
  297.  
  298.                "A bag of apples is NOT a bag of fruit".
  299.  
  300. If a bag of apples COULD be passed as a bag of fruit, someone could put a
  301. banana into the bag of apples!
  302.  
  303. ==============================================================================
  304.  
  305. Q48: Does array-of-Derived is-NOT-a-kind-of array-of-Base mean arrays are
  306.    bad?
  307.  
  308. Yes, "arrays are evil" (jest kidd'n :-).
  309.  
  310. There's a very subtle problem with using raw built-in arrays.  Consider this:
  311.  
  312.     void f(Base* arrayOfBase)
  313.     {
  314.       arrayOfBase[3].memberfn();
  315.     }
  316.  
  317.     main()
  318.     {
  319.       Derived arrayOfDerived[10];
  320.       f(arrayOfDerived);
  321.     }
  322.  
  323. The compiler thinks this is perfectly type-safe, since it can convert a
  324. Derived* to a Base*.  But in reality it is horrendously evil: since Derived
  325. might be larger than Base, the array index in f() not only isn't type safe, it
  326. may not even be pointing at a real object!  In general it'll be pointing
  327. somewhere into the innards of some poor Derived.
  328.  
  329. The root problem is that C++ can't distinguish between a ptr-to-a-thing and a
  330. ptr-to-an-array-of-things.  Naturally C++ "inherited" this feature from C.
  331.  
  332. NOTE: if we had used an array-like CLASS instead of using a raw array (e.g., an
  333. "Array<T>" rather than a "T[]"), this problem would have been properly trapped
  334. as an error at compile time rather than at run-time.
  335.  
  336. ==============================================================================
  337. SUBSECTION 12A: Inheritance -- Virtual functions
  338. ==============================================================================
  339.  
  340. Q49: What is a "virtual member function"?
  341.  
  342. A virtual function allows derived classes to replace the implementation
  343. provided by the base class.  The compiler ensures the replacement is always
  344. called whenever the object in question is actually of the derived class, even
  345. if the object is accessed by a base pointer rather than a derived pointer.
  346. This allows algorithms in the base class to be replaced in the derived class,
  347. even if users don't know about the derived class.
  348.  
  349. Note: the derived class can partially replace ("override") the base class
  350. method (the derived class method can invoke the base class version if desired).
  351.  
  352. ==============================================================================
  353.  
  354. Q50: How can C++ achieve dynamic binding yet also static typing?
  355.  
  356. In the following discussion, "ptr" means either a pointer or a reference.
  357.  
  358. When you have a ptr, there are two types: the (static) type of the ptr, and the
  359. (dynamic) type of the pointed-to object (the object may actually be of a class
  360. that is derived from the class of the ptr).
  361.  
  362. "Static typing" means that the "legality" of the call is checked based on the
  363. static type of the ptr: if the type of the ptr can handle the member fn,
  364. certainly the pointed-to object can handle it as well.
  365.  
  366. "Dynamic binding" means that the "code" that is called is based on the dynamic
  367. type of the pointed-to object.  This is called "dynamic binding," since the
  368. actual code being called is determined dynamically (at run time).
  369.  
  370. ==============================================================================
  371.  
  372. Q51: Should a derived class replace ("override") a non-virtual fn from a base
  373.    class?
  374.  
  375. It's legal, but it ain't moral.
  376.  
  377. Experienced C++ programmers will sometimes redefine a non-virtual fn for
  378. efficiency (the alternate implementation might make better use of the derived
  379. class' resources), or to get around the hiding rule (see below, and ARM
  380. sect.13.1).  However the client-visible effects must be IDENTICAL, since
  381. non-virtual fns are dispatched based on the static type of the ptr/ref rather
  382. than the dynamic type of the pointed-to/referenced object.
  383.  
  384. ==============================================================================
  385.  
  386. Q52: What's the meaning of, "Warning: Derived::f(int) hides Base::f(float)"?
  387.  
  388. It means you're going to die.
  389.  
  390. Here's the mess you're in: if Derived declares a member function named "f", and
  391. Base declares a member function named "f" with a different signature (e.g.,
  392. different parameter types and/or constness), then the Base "f" is "hidden"
  393. rather than "overloaded" or "overridden" (even if the Base "f" is virtual).
  394.  
  395. Here's how you get out of the mess: Derived must redefine the Base member
  396. function(s) that are hidden (even if they are non-virtual).  Normally this
  397. re-definition merely calls the appropriate Base member function.  E.g.,
  398.  
  399.     class Base {
  400.     public:
  401.       void f(int);
  402.     };
  403.  
  404.     class Derived : public Base {
  405.     public:
  406.       void f(double);
  407.       void f(int i) { Base::f(i); }
  408.     };             // ^^^^^^^^^^--- redefinition merely calls Base::f(int)
  409.  
  410. ==============================================================================
  411. SUBSECTION 12B: Inheritance -- Conformance
  412. ==============================================================================
  413.  
  414. Q53: Should I hide public member fns inherited from my base class?
  415.  
  416. Never, never, never do this.  Never.  NEVER!
  417.  
  418. Attempting to hide (eliminate, revoke) inherited public member functions is an
  419. all-too-common design error.  It usually stems from muddy thinking.
  420.  
  421. ==============================================================================
  422.  
  423. Q54: Is a "Circle" a kind-of an "Ellipse"?
  424.  
  425. Not if Ellipse promises to be able to change its size assymetrically.
  426.  
  427. For example, suppose Ellipse has a "setSize(x,y)" method, and suppose this
  428. method promises "the Ellipse's width() will be x, and its height() will be y".
  429. In this case, Circle can't be a kind-of Ellipse.  Simply put, if Ellipse can do
  430. something Circle can't, then Circle can't be a kind of Ellipse.
  431.  
  432. This leaves two potential (valid) relationships between Circle and Ellipse:
  433.  * Make Circle and Ellipse completely unrelated classes.
  434.  * Derive Circle and Ellipse from a base class representing "Ellipses that
  435.    can't NECESSARILY perform an unequal-setSize operation."
  436.  
  437. In the first case, Ellipse could be derived from class "AsymmetricShape" (with
  438. setSize(x,y) being introduced in AsymmetricShape), and Circle could be derived
  439. from "SymmetricShape," which has a setSize(size) member fn.
  440.  
  441. In the second case, class "Oval" could only have "setSize(size)" which sets
  442. both the "width()" and the "height()" to "size", then derive both Ellipse and
  443. Circle from Oval.  Ellipse --but not Circle-- adds the "setSize(x,y)" operation
  444. (see the "hiding rule" for a caveat if the same method name "setSize()" is used
  445. for both operations).
  446.  
  447. ==============================================================================
  448.  
  449. Q55: Are there other options to the "Circle is/isnot kind-of Ellipse"
  450.    dilemma?
  451.  
  452. If you claim that all Ellipses can be squashed assymetrically, and you claim
  453. that Circle is a kind-of Ellipse, and you claim that Circle can't be squashed
  454. assymetrically, clearly you've got to adjust (revoke, actually) one of your
  455. claims.  Thus you've either got to get rid of "Ellipse::setSize(x,y)", get rid
  456. of the inheritance relationship between Circle and Ellipse, or admit that your
  457. "Circle"s aren't necessarily circular.
  458.  
  459. Here are the two most common traps new OO/C++ programmers regularly fall into.
  460. They attempt to use coding hacks to cover up a broken design (they redefine
  461. Circle::setSize(x,y) to throw an exception, call "abort()", or choose the
  462. average of the two parameters, or to be a no-op).  Unfortunately all these
  463. hacks will surprise users, since users are expecting "width() == x" and
  464. "height() == y".
  465.  
  466. The only rational way out of this would be to weaken the promise made by
  467. Ellipse's "setSize(x,y)" (e.g., you'd have to change it to, "This method MIGHT
  468. set width() to x and height() to y, or it might do NOTHING").  Unfortunately
  469. this dilutes the contract into dribble, since the user can't rely on any
  470. meaningful behavior.  The whole hierarchy therefore begins to be worthless
  471. (it's hard to convince someone to use an object if you have to shrug your
  472. shoulders when asked what the object does for them).
  473.  
  474. ==============================================================================
  475. SUBSECTION 12C: Inheritance -- Access rules
  476. ==============================================================================
  477.  
  478. Q56: Why can't my derived class access "private" things from my base class?
  479.  
  480. To protect you from future changes to the base class.
  481.  
  482. Derived classes do not get access to private members of a base class.  This
  483. effectively "seals off" the derived class from any changes made to the private
  484. members of the base class.
  485.  
  486. ==============================================================================
  487.  
  488. Q57: What's the difference between "public:", "private:", and "protected:"?
  489.  
  490. "Private:" is discussed in the previous section, and "public:" means "anyone
  491. can access it."  The third option, "protected:", makes a member (either data
  492. member or member fn) accessible to subclasses.
  493.  
  494. ==============================================================================
  495.  
  496. Q58: How can I protect subclasses from breaking when I change internal parts?
  497.  
  498. A class has two distinct interfaces for two distinct sets of clients:
  499.  * its "public:" interface serves unrelated classes.
  500.  * its "protected:" interface serves derived classes.
  501.  
  502. Unless you expect all your subclasses to be built by your own team, you should
  503. consider making your base class's bits be "private:", and use "protected:"
  504. inline access functions to access these data.  This way the private bits can
  505. change, but the derived class's code won't break unless you change the
  506. protected access functions.
  507.  
  508. ==============================================================================
  509. SUBSECTION 12D: Inheritance -- Constructors and destructors
  510. ==============================================================================
  511.  
  512. Q59: When my base class's constructor calls a virtual function, why doesn't my
  513.    derived class's override of that virtual function get invoked?
  514.  
  515. During the Base class's constructor, the object isn't yet a Derived, so if
  516. "Base::Base()" calls a virtual function "virt()", the "Base::virt()" will be
  517. invoked, even if "Derived::virt()" exists.
  518.  
  519. Similarly, during Base's destructor, the object is no longer a Derived, so when
  520. Base::~Base() calls "virt()", "Base::virt()" gets control, NOT the
  521. "Derived::virt()" override.
  522.  
  523. You'll quickly see the wisdom of this approach when you imagine the disaster if
  524. "Derived::virt()" touched a member object from the Derived class.
  525.  
  526. ==============================================================================
  527.  
  528. Q60: Does a derived class destructor need to explicitly call the base
  529.    destructor?
  530.  
  531. No, never explicitly call a destructor (where "never" means "rarely").
  532.  
  533. A derived class's destructor (whether or not you explicitly define one)
  534. AUTOMATICALLY invokes the destructors for member objects and base class
  535. subobjects.  Member objects are destroyed in the reverse order they appear
  536. within the class, then base class subobjects are destroyed in the reverse order
  537. that they appear in the class's list of base classes.
  538.  
  539. You should ONLY explicitly call a destructor in esoteric situations, such as
  540. when destroying an object created by the "placement new operator."
  541.  
  542. ==============================================================================
  543. SUBSECTION 12E: Inheritance -- Private and protected inheritance
  544. ==============================================================================
  545.  
  546. Q61: How do you express "private inheritance"?
  547.  
  548. When you use ": private" instead of ": public."  E.g.,
  549.  
  550.     class Foo : private Bar {
  551.       //...
  552.     };
  553.  
  554. ==============================================================================
  555.  
  556. Q62: How are "private inheritance" and "composition" similar?
  557.  
  558. Private inheritance is a syntactic variant of composition (has-a).
  559.  
  560. E.g., the "car has-a engine" relationship can be expressed using composition:
  561.  
  562.     class Engine {
  563.     public:
  564.       Engine(int numCylinders);
  565.       void start();            //starts this Engine
  566.     };
  567.  
  568.     class Car {
  569.     public:
  570.       Car() : e_(8) { }        //initializes this Car with 8 cylinders
  571.       void start() { e_.start(); }    //start this Car by starting its engine
  572.     private:
  573.       Engine e_;
  574.     };
  575.  
  576. The same "has-a" relationship can also be expressed using private inheritance:
  577.  
  578.     class Car : private Engine {
  579.     public:
  580.       Car() : Engine(8) { }        //initializes this Car with 8 cylinders
  581.       Engine::start;        //start this Car by starting its engine
  582.     };
  583.  
  584. There are several similarities between these two forms of composition:
  585.  * in both cases there is exactly one Engine member object contained in a Car.
  586.  * in neither case can users (outsiders) convert a Car* to an Engine*.
  587.  
  588. There are also several distinctions:
  589.  * the second form is needed if you want to contain several Engines per Car.
  590.  * the first form can introduce unnecessary multiple inheritance.
  591.  * the first form allows members of Car to convert a Car* to an Engine*.
  592.  * the first form allows access to the "protected" members of the base class.
  593.  * the first form allows Car to override Engine's virtual functions.
  594.  
  595. Note that private inheritance is usually used to gain access into the
  596. "protected:" members of the base class, but this is usually a short-term
  597. solution (translation: a band-aid; see below).
  598.  
  599. ==============================================================================
  600.  
  601. Q63: Which should I prefer: composition or private inheritance?
  602.  
  603. Composition.
  604.  
  605. Normally you don't WANT to have access to the internals of too many other
  606. classes, and private inheritance gives you some of this extra power (and
  607. responsibility).  But private inheritance isn't evil; it's just more expensive
  608. to maintain, since it increases the probability that someone will change
  609. something that will break your code.
  610.  
  611. A legitimate, long-term use for private inheritance is when you want to build a
  612. class Fred that uses code in a class Wilma, and the code from class Wilma needs
  613. to invoke methods from your new class, Fred.  In this case, Fred calls
  614. non-virtuals in Wilma, and Wilma calls (usually pure) virtuals in itself, which
  615. are overridden by Fred.  This would be much harder to do with composition.
  616.  
  617.     class Wilma {
  618.     protected:
  619.       void fredCallsWilma()
  620.         { cout << "Wilma::fredCallsWilma()\n"; wilmaCallsFred(); }
  621.       virtual void wilmaCallsFred() = 0;
  622.     };
  623.  
  624.     class Fred : private Wilma {
  625.     public:
  626.       void barney()
  627.         { cout << "Fred::barney()\n"; Wilma::fredCallsWilma(); }
  628.     protected:
  629.       virtual void wilmaCallsFred()
  630.         { cout << "Fred::wilmaCallsFred()\n"; }
  631.     };
  632.  
  633. ==============================================================================
  634.  
  635. Q64: Should I pointer-cast from a "privately" derived class to its base
  636.    class?
  637.  
  638. Generally, No.
  639.  
  640. From a method or friend of a privately derived class, the relationship to the
  641. base class is known, and the upward conversion from PrivatelyDer* to Base* (or
  642. PrivatelyDer& to Base&) is safe; no cast is needed or recommended.
  643.  
  644. However users of PrivateDer should avoid this unsafe conversion, since it is
  645. based on a "private" decision of PrivateDer, and is subject to change without
  646. notice.
  647.  
  648. ==============================================================================
  649.  
  650. Q65: How is protected inheritance related to private inheritance?
  651.  
  652. Similarities: both allow overriding virtuals in the private/protected base
  653. class, neither claims the derived is a kind-of its base.
  654.  
  655. Dissimilarities: protected inheritance allows derived classes of derived
  656. classes to know about the inheritance relationship (it exposes your grand kids
  657. to your implementation details).  This has both benefits (it allows subclasses
  658. of the protected derived class to exploit the relationship to the protected
  659. base class) and costs (the protected derived class can't change the
  660. relationship without potentially breaking further derived classes).
  661.  
  662. Protected inheritance uses the ": protected" syntax:
  663.  
  664.     class Car : protected Engine {
  665.       //...
  666.     };
  667.  
  668. ==============================================================================
  669.  
  670. Q66: What are the access rules with "private" and "protected" inheritance?
  671.  
  672. Take these classes as examples:
  673.  
  674.     class B                    { /*...*/ };
  675.     class D_priv : private   B { /*...*/ };
  676.     class D_prot : protected B { /*...*/ };
  677.     class D_publ : public    B { /*...*/ };
  678.     class UserClass            { B b; /*...*/ };
  679.  
  680. None of the subclasses can access anything that is private in B.  In D_priv,
  681. the public and protected parts of B are "private".  In D_prot, the public and
  682. protected parts of B are "protected".  In D_publ, the public parts of B are
  683. public and the protected parts of B are protected (D_publ is-a-kind-of-a B).
  684. Class "UserClass" can only access the public parts of B, which "seals off"
  685. UserClass from B.
  686.  
  687. To make a public member of B so it is public in D_priv or D_prot, state the
  688. name of the member with a "B::" prefix.  E.g., to make member "B::f(int,float)"
  689. public in D_prot, you would say:
  690.  
  691.     class D_prot : protected B {
  692.     public:
  693.       B::f;    //note: not  "B::f(int,float)"
  694.     };
  695.  
  696. ==============================================================================
  697. SECTION 13: Abstraction
  698. ==============================================================================
  699.  
  700. Q67: What's the big deal of separating interface from implementation?
  701.  
  702. Interfaces are a company's most valuable resources.  Designing an interface
  703. takes longer than whipping together a concrete class which fulfills that
  704. interface.  Furthermore interfaces require the time of more expensive people.
  705.  
  706. Since interfaces are so valuable, they should be protected from being tarnished
  707. by data structures and other implementation artifacts.  Thus you should
  708. separate interface from implementation.
  709.  
  710. ==============================================================================
  711.  
  712. Q68: How do I separate interface from implementation in C++ (like Modula-2)?
  713.  
  714. Use an ABC (see next FAQ).
  715.  
  716. ==============================================================================
  717.  
  718. Q69: What is an ABC ("abstract base class")?
  719.  
  720. At the design level, an ABC corresponds to an abstract concept.  If you asked a
  721. Mechanic if he repaired Vehicles, he'd probably wonder what KIND-OF Vehicle you
  722. had in mind.  Chances are he doesn't repair space shuttles, ocean liners,
  723. bicycles, or nuclear submarines.  The problem is that the term "Vehicle" is an
  724. abstract concept (e.g., you can't build a "vehicle" unless you know what kind
  725. of vehicle to build).  In C++, class Vehicle would be an ABC, with Bicycle,
  726. SpaceShuttle, etc, being subclasses (an OceanLiner is-a-kind-of-a Vehicle).  In
  727. real-world OOP, ABCs show up all over the place.
  728.  
  729. As programming language level, an ABC is a class that has one or more pure
  730. virtual member functions (see next FAQ).  You cannot make an object (instance)
  731. of an ABC.
  732.  
  733. ==============================================================================
  734.  
  735. Q70: What is a "pure virtual" member function?
  736.  
  737. A member function of an ABC that you can only implement in a derived class.
  738.  
  739. Some member functions exist in concept, but can't have any actual defn.  E.g.,
  740. suppose I asked you to draw a Shape at location (x,y) that has size 7.  You'd
  741. ask me "what kind of shape should I draw?" (circles, squares, hexagons, etc,
  742. are drawn differently).  In C++, we indicate the existence of the "draw()'
  743. method, but we recognize it can only be defined in subclasses:
  744.  
  745.     class Shape {
  746.     public:
  747.       virtual void draw() const = 0;
  748.       //...                     ^^^--- "= 0" means it is "pure virtual"
  749.     };
  750.  
  751. This pure virtual function makes "Shape" an ABC.  If you want, you can think of
  752. the "= 0" syntax as if if the code were at the NULL pointer.  Thus "Shape"
  753. promises a service to its users, yet Shape isn't able to provide any code to
  754. fulfill that promise.  This ensures any actual object created from a [concrete]
  755. class derived of Shape *WILL* have the indicated member fn, even though the
  756. base class doesn't have enough information to actually DEFINE it yet.
  757.  
  758. ==============================================================================
  759.  
  760. Q71: How can I provide printing for an entire hierarchy of classes?
  761.  
  762. Provide a friend operator<< that calls a protected virtual function:
  763.  
  764.     class Base {
  765.     public:
  766.       friend ostream& operator<< (ostream& o, const Base& b)
  767.         { b.print(o); return o; }
  768.       //...
  769.     protected:
  770.       virtual void print(ostream& o) const;  //or "=0;" if "Base" is an ABC
  771.     };
  772.  
  773.     class Derived : public Base {
  774.     protected:
  775.       virtual void print(ostream& o) const;
  776.     };
  777.  
  778. Now all subclasses of Base merely provide their own "print(ostream&) const"
  779. member function (they all share the common "<<" operator).  This technique
  780. allows friends to ACT as if they supported dynamic binding.
  781.  
  782. ==============================================================================
  783.  
  784. Q72: When should my destructor be virtual?
  785.  
  786. When you may "delete" a derived object via a base pointer.
  787.  
  788. Virtual fns bind to the code associated with the class of the object, rather
  789. than with the class of the pointer/ref.  When you say "delete basePtr", and the
  790. base class has a virtual destructor, the destructor that gets invoked is the
  791. one associated with the type of the object *basePtr, rather than the one
  792. associated with the type of the pointer.  This is generally A Good Thing.
  793.  
  794. To make life easy for you, the only time you wouldn't want to make a class's
  795. destructor virtual is if that class has NO virtual fns, since the introduction
  796. of the first virtual fn imposes some space overhead in each object (typically
  797. one machine word).  This is how the compiler implements the magic of dynamic
  798. binding; it usually boils down to an extra ptr per object called the "virtual
  799. table pointer" or "vptr".
  800.  
  801. ==============================================================================
  802.  
  803. Q73: What is a "virtual constructor"?
  804.  
  805. An idiom that allows you to do something that C++ doesn't directly support.
  806.  
  807. You can get the effect of virtual constructor by a virtual "createCopy()"
  808. member fn (for copy constructing), or a virtual "createSimilar()" member fn
  809. (for the default constructor).
  810.  
  811.     class Shape {
  812.     public:
  813.       virtual ~Shape() { }        //see on "virtual destructors" for more
  814.       virtual void draw() = 0;
  815.       virtual void move() = 0;
  816.       //...
  817.       virtual Shape* createCopy() const = 0;
  818.       virtual Shape* createSimilar() const = 0;
  819.     };
  820.  
  821.     class Circle : public Shape {
  822.     public:
  823.       Circle* createCopy()    const { return new Circle(*this); }
  824.       Circle* createSimilar() const { return new Circle(); }
  825.       //...
  826.     };
  827.  
  828. The invocation of "Circle(*this)" is that of copy construction ("*this" has
  829. type "const Circle&" in these methods).  "createSimilar()" is similar, but it
  830. constructs a "default" Circle.
  831.  
  832. Users use these as if they were "virtual constructors":
  833.  
  834.     void userCode(Shape& s)
  835.     {
  836.       Shape* s2 = s.createCopy();
  837.       Shape* s3 = s.createSimilar();
  838.       //...
  839.       delete s2;    //relies on destructor being virtual!!
  840.       delete s3;    // ditto
  841.     }
  842.  
  843. This fn will work correctly regardless of whether the Shape is a Circle,
  844. Square, or some other kind-of Shape that doesn't even exist yet.
  845.  
  846. --
  847. Marshall Cline
  848. --
  849. Marshall P. Cline, Ph.D. / Paradigm Shift Inc / PO Box 5108 / Potsdam NY 13676
  850. cline@sun.soe.clarkson.edu / 315-353-6100 / FAX: 315-353-6110
  851.